/* eslint jsx-a11y/no-static-element-interactions: warn */

/* eslint jsx-a11y/click-events-have-key-events: warn */
import * as DropdownMenu from '@radix-ui/react-dropdown-menu';
import { useDynamicConfig, useGateValue } from '@statsig/react-bindings';
import clsx from 'clsx';
import { observer } from 'mobx-react-lite';
import { useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';

import { useStores } from '@/app/(root)/AppProviders';
import Button, {
  ButtonShape,
  ButtonSize,
  ButtonVariant,
} from '@/components/button/Button';
import ImageWithFallback from '@/components/image/ImageWithFallback';
import Link from '@/components/link/Link';
import { ModalTypes } from '@/components/modal/constants/ModalTypes';
import VerifiedBadge from '@/components/timbaland/VerifiedBadge';
import { toast } from '@/components/toast/Toast';
import { useModalContext } from '@/context/ModalContext';
import { useBreakpointMd } from '@/hooks/useBreakpoint';
import { useCreatorLabel } from '@/hooks/useCreatorLabel';
import {
  CheckIcon,
  EditIcon,
  InstagramIcon,
  MoreVerticalIcon,
  PauseIcon,
  PlayIcon,
  ProhibitionIcon,
  ShareArrowIcon,
  SoundcloudIcon,
  SpotifyIcon,
  StarIcon,
  ThumbsUpIcon,
  TwitterXIcon,
  UserAddIcon,
  UserAddedIcon,
  YoutubeIcon,
} from '@/icons';
import CreditCardIcon from '@/icons/generated/CreditCardIcon';
import { useApiClient } from '@/lib/apiClient';
import { ContextType } from '@/logging/contextTypes';
import logWebUserEvent from '@/logging/logWebUserEvent';
import { Clip } from '@/state/clipStore';
import { SessionStore } from '@/state/sessionStore';
import { LARGE_IMAGE } from '@/utils/constants';
import { CreatorLabel } from '@/utils/constants';
import { shareProfile } from '@/utils/download';
import {
  getCountString,
  isSecretStatsProfile,
  isVerifiedProfile,
} from '@/utils/utils';

const MAX_TAG_LENGTH = 20;

interface ProfileHeaderProps {
  profile: any;
  session: SessionStore;
  isFlagged: boolean;
  followerCount: number;
  followingCount: number;
  playCount: number;
  upvoteCount: number;
  onFollow: () => void;
  isFollowing: boolean;
  isBlockedByProfile: boolean;
  isBlockingProfile: boolean;
  onBlock: () => void;
  clips: Clip[];
  remixesInspiredCount: number;
  onEdit: () => void;
  onOpenFollowers?: () => void;
  onOpenFollowing?: () => void;
  onOpenRemixesInspired?: () => void;
  hookCreatorLabel?: string;
}

const HeaderButtons = ({
  handle,
  display_name,
  user_id,
  clips,
  isFollowing,
  onFollow,
  isBlockedByProfile,
  isBlockingProfile,
  onBlock,
  onEdit,
  hookCreatorLabel,
}: {
  handle: string;
  display_name: string;
  user_id: string;
  clips: Clip[];
  isFollowing: boolean;
  onFollow: () => void;
  isBlockedByProfile: boolean;
  isBlockingProfile: boolean;
  onBlock: () => void;
  onEdit: () => void;
  hookCreatorLabel?: string;
}) => {
  const { t } = useTranslation();
  const { playbar, session, queue: queueStore } = useStores();
  const apiClient = useApiClient();
  const { openModalWithData } = useModalContext();
  const [isMenuOpen, setIsMenuOpen] = useState(false);

  // Local state to track the current creator label
  const [currentCreatorLabel, setCurrentCreatorLabel] = useState<
    string | undefined
  >(hookCreatorLabel);

  // Update local state when prop changes
  useEffect(() => {
    setCurrentCreatorLabel(hookCreatorLabel);
  }, [hookCreatorLabel]);

  // Creator label mutations
  const { setCreatorLabelMutation, removeCreatorLabelMutation } =
    useCreatorLabel({
      setCurrentCreatorLabel,
    });

  const handleBlockClick = () => {
    onBlock();
    setIsMenuOpen(false);
  };

  const handleShareClick = () => {
    logWebUserEvent(
      {
        actionName: 'ArtistProfileShareToClicked',
        context: {
          profileHandle: handle,
        },
      },
      session
    );

    openModalWithData(
      ModalTypes.SHARE_CLIP,
      {
        profileHandle: handle,
      },
      'ProfileHeader'
    );
    setIsMenuOpen(false);
  };

  const handleAddCreditsClick = async () => {
    try {
      if (!session.userId) {
        console.error('User ID not available');
        return;
      }

      const response = await apiClient.POST('/api/billing/add-credits/', {
        body: {
          user_id: user_id as any,
          credit_amount: 1000,
        },
      });

      if (response.data) {
        console.log('Credits added successfully:', response.data);
        toast({
          title: 'Credits Added Successfully',
          description: '1000 credits have been added to the user account.',
          status: 'success',
          position: 'bottom',
          duration: 5000,
          isClosable: true,
        });
      } else {
        console.error('Failed to add credits:', response);
        toast({
          title: 'Failed to Add Credits',
          description: 'There was an error adding credits to the account.',
          status: 'error',
          position: 'bottom',
          duration: 5000,
          isClosable: true,
        });
      }
    } catch (error) {
      console.error('Error adding credits:', error);
      toast({
        title: 'Failed to Add Credits',
        description: 'There was an error adding credits to the account.',
        status: 'error',
        position: 'bottom',
        duration: 5000,
        isClosable: true,
      });
    }
    setIsMenuOpen(false);
  };

  const handleAddChampionLabelClick = async () => {
    // Check if already champion
    if (currentCreatorLabel === CreatorLabel.CHAMPION) {
      toast({
        title: 'Already Champion',
        description: 'Creator is already Champion.',
        status: 'info',
        position: 'bottom',
        duration: 3000,
        isClosable: true,
      });
      setIsMenuOpen(false);
      return;
    }

    setCreatorLabelMutation.mutate({
      creator_user_uuid: user_id,
      label: CreatorLabel.CHAMPION,
    });
    setIsMenuOpen(false);
  };

  const handleAddAmbassadorLabelClick = async () => {
    // Check if already ambassador
    if (currentCreatorLabel === CreatorLabel.AMBASSADOR) {
      toast({
        title: 'Already Ambassador',
        description: 'Creator is already Ambassador.',
        status: 'info',
        position: 'bottom',
        duration: 3000,
        isClosable: true,
      });
      setIsMenuOpen(false);
      return;
    }

    setCreatorLabelMutation.mutate({
      creator_user_uuid: user_id,
      label: CreatorLabel.AMBASSADOR,
    });
    setIsMenuOpen(false);
  };

  const handleRemoveHookCreatorLabelClick = async () => {
    // Check if already no label
    if (!currentCreatorLabel) {
      toast({
        title: 'No Label to Remove',
        description: 'Creator already has no label.',
        status: 'info',
        position: 'bottom',
        duration: 3000,
        isClosable: true,
      });
      setIsMenuOpen(false);
      return;
    }

    removeCreatorLabelMutation.mutate({
      creator_user_uuid: user_id,
    });
    setIsMenuOpen(false);
  };

  const canAddHookCreatorLabel =
    useGateValue('enable-hook-creator-label') && session.isStaff;

  const isChampion = currentCreatorLabel === CreatorLabel.CHAMPION;
  const isAmbassador = currentCreatorLabel === CreatorLabel.AMBASSADOR;
  const isNoLabel = !currentCreatorLabel;

  return (
    <section className='flex flex-row justify-between'>
      <div className='flex flex-row gap-2'>
        {handle && session.user?.handle && handle !== session.user?.handle && (
          <>
            {isBlockingProfile ? (
              <Button
                variant={ButtonVariant.LightSecondary}
                size={ButtonSize.Medium}
                shape={ButtonShape.Pill}
                disabled
                className='bg-accent-error px-[12px] text-[16px] font-medium text-white'
              >
                {t('profile.blocked')}
              </Button>
            ) : (
              !isBlockedByProfile && (
                <Button
                  variant={ButtonVariant.LightSecondary}
                  size={ButtonSize.Medium}
                  shape={ButtonShape.Pill}
                  active={isFollowing}
                  icon={isFollowing ? UserAddedIcon : UserAddIcon}
                  onClick={onFollow}
                  className='px-[12px] text-[16px] font-medium'
                >
                  {isFollowing ? t('profile.following') : t('profile.follow')}
                </Button>
              )
            )}
          </>
        )}
        {handle && session.user?.handle && handle === session.user?.handle && (
          <>
            {session.isStaff && (
              <Button
                variant={ButtonVariant.Primary}
                size={ButtonSize.Medium}
                shape={ButtonShape.Pill}
                onClick={handleAddCreditsClick}
                className='bg-accent-brand px-[12px] text-[16px] font-medium text-white'
                contentClassName='gap-[4px]'
              >
                Add Credits
              </Button>
            )}
            <Button
              variant={ButtonVariant.Primary}
              size={ButtonSize.Medium}
              iconStart={EditIcon}
              shape={ButtonShape.Pill}
              onClick={() => {
                logWebUserEvent(
                  {
                    actionName: 'ArtistProfileEditButtonClicked',
                    context: {
                      source: 'profile-page',
                    },
                  },
                  session
                );
                onEdit();
              }}
              className='px-[12px] text-[16px] font-medium'
              contentClassName='gap-[4px]'
            >
              Edit
            </Button>
          </>
        )}
        {!isBlockingProfile && !isBlockedByProfile && clips.length ? (
          <Button
            variant={ButtonVariant.LightSecondary}
            size={ButtonSize.Medium}
            shape={ButtonShape.Pill}
            icon={
              queueStore.contextType === ContextType.Profile &&
              queueStore.contextId === user_id &&
              playbar.isPlaying
                ? PauseIcon
                : PlayIcon
            }
            onClick={() => {
              logWebUserEvent(
                {
                  actionName: 'ArtistProfilePlayButtonClicked',
                  context: {
                    source: 'header',
                    songId: clips[0]?.id,
                    songTitle: clips[0]?.title,
                  },
                },
                session
              );

              if ((clips || []).length > 0) {
                if (
                  queueStore.contextType === ContextType.Profile &&
                  queueStore.contextId === user_id
                ) {
                  playbar.togglePlay();
                  return;
                }
                queueStore.setPlayContext({
                  contextType: ContextType.Profile,
                  contextId: user_id,
                  clips,
                  currentIndex: 0,
                });
                playbar.playClip(clips[0]);
              }
            }}
          />
        ) : null}
        {!isBlockingProfile && !isBlockedByProfile && (
          <Button
            variant={ButtonVariant.LightSecondary}
            size={ButtonSize.Medium}
            icon={ShareArrowIcon}
            shape={ButtonShape.Pill}
            onClick={() => {
              logWebUserEvent(
                {
                  actionName: 'ArtistProfileShareButtonClicked',
                  context: {
                    profileHandle: handle,
                  },
                },
                session
              );

              shareProfile({
                handle,
                display_name: display_name,
              });
            }}
          />
        )}
        {handle &&
          session.user?.handle &&
          handle !== session.user?.handle &&
          !isBlockedByProfile && (
            <DropdownMenu.Root open={isMenuOpen} onOpenChange={setIsMenuOpen}>
              <DropdownMenu.Trigger asChild>
                <Button
                  variant={ButtonVariant.LightSecondary}
                  size={ButtonSize.Medium}
                  shape={ButtonShape.Pill}
                  className='flex h-11 w-11 items-center justify-center p-0 hover:cursor-pointer'
                >
                  <MoreVerticalIcon className='h-5 w-5' />
                </Button>
              </DropdownMenu.Trigger>
              <DropdownMenu.Portal>
                <DropdownMenu.Content
                  align='end'
                  className={clsx(
                    'flex flex-col items-start justify-start gap-1 rounded-md border',
                    'z-10 min-w-[160px] overflow-clip',
                    'md:box-shadow border-border-primary bg-background-tertiary text-foreground-secondary',
                    'font-sans text-sm font-medium'
                  )}
                >
                  <DropdownMenu.Item onSelect={handleShareClick} asChild>
                    <Button
                      className='w-full'
                      contentClassName='justify-start'
                      icon={ShareArrowIcon}
                      variant={ButtonVariant.Tertiary}
                    >
                      {t('Share to...')}
                    </Button>
                  </DropdownMenu.Item>
                  <DropdownMenu.Item onSelect={handleBlockClick} asChild>
                    <Button
                      className='w-full'
                      contentClassName='justify-start'
                      icon={ProhibitionIcon}
                      variant={ButtonVariant.Tertiary}
                    >
                      {isBlockingProfile
                        ? t('actions.unblock')
                        : t('actions.block')}
                    </Button>
                  </DropdownMenu.Item>
                  {session.isStaff && (
                    <DropdownMenu.Item onSelect={handleAddCreditsClick} asChild>
                      <Button
                        className='w-full border border-border-primary bg-accent-brand font-medium text-white'
                        contentClassName='justify-start'
                        icon={CreditCardIcon}
                        variant={ButtonVariant.Tertiary}
                      >
                        Add Credits
                      </Button>
                    </DropdownMenu.Item>
                  )}
                  {canAddHookCreatorLabel && (
                    <DropdownMenu.Sub>
                      <DropdownMenu.SubTrigger asChild>
                        <Button
                          className='w-full'
                          contentClassName='justify-start'
                          icon={StarIcon}
                          variant={ButtonVariant.Tertiary}
                        >
                          Creator label (staff only)
                        </Button>
                      </DropdownMenu.SubTrigger>
                      <DropdownMenu.Portal>
                        <DropdownMenu.SubContent
                          className={clsx(
                            'flex flex-col items-start justify-start gap-1 rounded-md border',
                            'z-10 min-w-[160px] overflow-clip',
                            'md:box-shadow border-border-primary bg-background-tertiary text-foreground-secondary',
                            'font-sans text-sm font-medium'
                          )}
                          sideOffset={2}
                          alignOffset={-5}
                        >
                          <DropdownMenu.Item
                            onSelect={handleRemoveHookCreatorLabelClick}
                            asChild
                          >
                            <Button
                              className='w-full'
                              contentClassName='justify-start'
                              icon={isNoLabel ? CheckIcon : undefined}
                              variant={ButtonVariant.Tertiary}
                            >
                              No Label
                            </Button>
                          </DropdownMenu.Item>
                          <DropdownMenu.Item
                            onSelect={handleAddChampionLabelClick}
                            asChild
                          >
                            <Button
                              className='w-full'
                              contentClassName='justify-start'
                              icon={isChampion ? CheckIcon : undefined}
                              variant={ButtonVariant.Tertiary}
                            >
                              Champion
                            </Button>
                          </DropdownMenu.Item>
                          <DropdownMenu.Item
                            onSelect={handleAddAmbassadorLabelClick}
                            asChild
                          >
                            <Button
                              className='w-full'
                              contentClassName='justify-start'
                              icon={isAmbassador ? CheckIcon : undefined}
                              variant={ButtonVariant.Tertiary}
                            >
                              Ambassador
                            </Button>
                          </DropdownMenu.Item>
                        </DropdownMenu.SubContent>
                      </DropdownMenu.Portal>
                    </DropdownMenu.Sub>
                  )}
                </DropdownMenu.Content>
              </DropdownMenu.Portal>
            </DropdownMenu.Root>
          )}
      </div>
    </section>
  );
};

const ProfileMetadata = ({
  playCount,
  upvoteCount,
  display_name,
  handle,
  user_id,
  profile_description,
  userTags,
  spotify_link,
  soundcloud_link,
  x_link,
  instagram_link,
  youtube_link,
  isFlagged,
  className,
  followerCount,
  followingCount,
  isFollowing,
  onFollow,
  isBlockedByProfile,
  isBlockingProfile,
  onBlock,
  clips,
  remixesInspiredCount,
  onEdit,
  onOpenFollowers,
  onOpenFollowing,
  onOpenRemixesInspired,
  hookCreatorLabel,
}: {
  playCount: number;
  upvoteCount: number;
  userTags: string[];
  display_name: string;
  handle: string;
  user_id: string;
  profile_description: string;
  spotify_link: string;
  soundcloud_link: string;
  x_link: string;
  instagram_link: string;
  youtube_link: string;
  isFlagged: boolean;
  className?: string;
  followerCount: number;
  followingCount: number;
  isFollowing: boolean;
  onFollow: () => void;
  isBlockedByProfile: boolean;
  isBlockingProfile: boolean;
  onBlock: () => void;
  onEdit: () => void;
  clips: Clip[];
  remixesInspiredCount: number;
  onOpenFollowers?: () => void;
  onOpenFollowing?: () => void;
  onOpenRemixesInspired?: () => void;
  hookCreatorLabel?: string;
}) => {
  const { session } = useStores();
  const [isDescriptionExpanded, setIsDescriptionExpanded] = useState(false);
  const { value: verifiedProfiles } = useDynamicConfig('verified-profiles');
  const handles = (verifiedProfiles?.handles as string[]) || [];

  const showRemixesInspired = remixesInspiredCount > 0;
  const isTablet = useBreakpointMd();

  const truncationLimit = isTablet ? 68 : 40;

  const shouldTruncateDescription =
    profile_description && profile_description.length > truncationLimit;

  const displayDescription =
    shouldTruncateDescription && !isDescriptionExpanded
      ? profile_description.substring(0, truncationLimit)
      : profile_description;

  // Add this helper function to ensure URLs have proper protocol
  const renderSocialLink = (url: string, icon: React.ReactNode) => {
    if (!url) return null;

    // Add https:// if no protocol is present
    const finalUrl = /^https?:\/\//.test(url.trim())
      ? url.trim()
      : `https://${url.trim()}`;

    return (
      <Link href={finalUrl} target='_blank' rel='noopener noreferrer'>
        {icon}
      </Link>
    );
  };

  // Extract and process styles from clips
  const getStyleTags = (clips: Clip[]) => {
    if (!clips || clips.length === 0) return [];

    // Extract all styles from clips
    const styleCount = new Map<string, number>();

    clips.forEach((clip) => {
      if (
        clip.metadata?.tags &&
        clip.metadata.tags?.toLowerCase() !== 'no style'
      ) {
        const tags = clip.metadata.tags;
        tags.split(',').forEach((tag) => {
          styleCount.set(tag, (styleCount.get(tag) || 0) + 1);
        });
      }
    });

    // Sort by frequency and return top styles
    return Array.from(styleCount.entries())
      .sort((a, b) => b[1] - a[1]) // Sort by count descending
      .slice(0, 5) // Take top 5
      .map(([style]) => style);
  };

  const tags = useMemo(() => {
    return getStyleTags(clips);
  }, [clips]);

  const renderTag = (tag: string) => {
    const truncatedTag =
      tag.length > MAX_TAG_LENGTH
        ? tag.substring(0, MAX_TAG_LENGTH) + '...'
        : tag;
    return (
      <span className='mr-1 inline-block rounded-md bg-background-fog-thick px-2 py-1 text-xs leading-4 font-normal text-foreground-primary-on-dark'>
        {truncatedTag}
      </span>
    );
  };

  const renderSeperator = (className?: string) => {
    return (
      <span
        className={clsx(
          'mx-[8px] flex flex-row items-center gap-[4px] text-[rgba(255,255,255,0.15)]',
          className
        )}
      >
        |
      </span>
    );
  };

  const hasSocialLinks =
    spotify_link || soundcloud_link || x_link || instagram_link || youtube_link;

  const hasUserTags = userTags?.length > 0 || tags?.length > 0;

  return (
    <section className={clsx(className, 'flex flex-col gap-2')}>
      <div className='flex flex-col gap-2 md:flex-row'>
        <div className='flex-1'>
          <span className='flex w-full flex-row items-center gap-2'>
            <div className='flex-1 text-center font-sans text-[40px] leading-[48px] font-medium text-[#FAF7F5] md:text-left'>
              <span className=''>
                {!isFlagged ? display_name || `@${handle}` : 'Anonymous User'}
                {isVerifiedProfile({ handle }, handles) && (
                  <span className='ml-2 inline-block'>
                    <VerifiedBadge />
                  </span>
                )}
              </span>
            </div>
          </span>
          <div className='mt-0 flex flex-col gap-2 text-center font-sans text-[14px] leading-[20px] font-normal text-[rgba(255,255,255,0.75)] md:mt-2 md:flex-row md:gap-0 md:text-left'>
            <div className='text-[16px]'>@{handle}</div>
            <div className='hidden md:block'>
              {hasUserTags || hasSocialLinks ? renderSeperator() : null}
            </div>

            {hasSocialLinks && (
              <div className='flex flex-row items-center justify-center gap-[4px] md:justify-start'>
                {renderSocialLink(
                  spotify_link,
                  <SpotifyIcon className='h-[16px] w-[16px] text-[#02D95C]' />
                )}
                {renderSocialLink(
                  soundcloud_link,
                  <SoundcloudIcon className='h-[16px] w-[16px] text-[#FF6A00]' />
                )}
                {renderSocialLink(
                  x_link,
                  <TwitterXIcon className='h-[16px] w-[16px] text-[#FFFFFF]' />
                )}
                {renderSocialLink(
                  instagram_link,
                  <InstagramIcon className='h-[16px] w-[16px] text-[#FD429C]' />
                )}
                {renderSocialLink(
                  youtube_link,
                  <YoutubeIcon className='h-[16px] w-[16px] text-[#FF0000]' />
                )}
              </div>
            )}

            {hasSocialLinks && hasUserTags && (
              <div className='hidden md:block'>{renderSeperator()}</div>
            )}
            <div className='flex-1'>
              {userTags?.length > 0
                ? userTags?.slice(0, 5).map(renderTag)
                : tags?.slice(0, 5).map(renderTag)}
            </div>
          </div>
          <p className='mx-auto mt-2 max-w-[515px] px-4 text-center font-sans text-[16px] leading-[20px] font-normal text-[rgba(255,255,255,0.75)] md:mx-0 md:mt-1 md:px-0 md:text-left'>
            <span>
              {displayDescription}
              {shouldTruncateDescription && (
                <button
                  onClick={() => {
                    setIsDescriptionExpanded(!isDescriptionExpanded);
                    logWebUserEvent(
                      {
                        actionName: 'ArtistProfileBioExpandClicked',
                        context: {
                          profileHandle: handle,
                          action: isDescriptionExpanded ? 'collapse' : 'expand',
                          bioLength: profile_description.length,
                        },
                      },
                      session
                    );
                  }}
                  className='ml-1 cursor-pointer text-[rgba(255,255,255,0.9)] underline hover:text-white'
                >
                  {isDescriptionExpanded ? 'less' : '...more'}
                </button>
              )}
            </span>
          </p>
          <div
            className={`flex ${showRemixesInspired ? 'flex-col md:flex-row' : 'flex-row'} mt-2 mb-3 justify-center gap-[0px] text-center md:justify-start md:text-left`}
          >
            <div className='flex flex-row justify-center gap-[0px] md:justify-start'>
              <div
                className='flex cursor-pointer flex-row items-center gap-[4px] transition-opacity hover:opacity-80'
                onClick={onOpenFollowers}
              >
                <div className='text-[16px] leading-[20px] font-medium text-foreground-primary-on-dark'>
                  {getCountString(followerCount)}
                </div>
                <div className='text-[16px] leading-[20px] font-normal text-foreground-secondary-glass'>
                  Followers
                </div>
              </div>
              <div className='h-[16px] w-[8px] bg-none' />

              <div
                className='flex cursor-pointer flex-row items-center gap-[4px] transition-opacity hover:opacity-80'
                onClick={onOpenFollowing}
              >
                <div className='text-[16px] leading-[20px] font-medium text-foreground-primary-on-dark'>
                  {getCountString(followingCount)}
                </div>
                <div className='text-[16px] leading-[20px] font-normal text-foreground-secondary-glass'>
                  Following
                </div>
              </div>
              {showRemixesInspired && (
                <>
                  <div className='h-[16px] w-[8px] bg-none' />
                  <div
                    className='flex cursor-pointer flex-row items-center gap-[4px] transition-opacity hover:opacity-80'
                    onClick={onOpenRemixesInspired}
                  >
                    <div className='text-[16px] leading-[20px] font-medium text-foreground-primary-on-dark'>
                      {getCountString(remixesInspiredCount)}
                    </div>
                    <div className='text-[16px] leading-[20px] font-normal text-foreground-secondary-glass'>
                      Remixes Inspired
                    </div>
                  </div>
                </>
              )}
            </div>

            {/* Separator - only visible on desktop when remixes are shown, always visible when remixes not shown */}
            <div className={showRemixesInspired ? 'hidden md:flex' : 'flex'}>
              {!isSecretStatsProfile({ handle }) && renderSeperator('mr-1')}
            </div>

            {!isSecretStatsProfile({ handle }) && (
              <div className='flex flex-row items-center justify-center gap-[8px] md:justify-start'>
                <div className='flex flex-row items-center gap-[4px]'>
                  <PlayIcon className='h-[16px] w-[16px] text-foreground-secondary-glass' />
                  <div className='text-[16px] leading-[20px] font-medium font-normal text-foreground-primary-on-dark'>
                    {getCountString(playCount)}
                  </div>
                </div>
                <div className='flex flex-row items-center gap-[4px]'>
                  <ThumbsUpIcon className='h-[16px] w-[16px] text-foreground-secondary-glass' />
                  <div className='text-[16px] leading-[20px] font-medium font-normal text-foreground-primary-on-dark'>
                    {getCountString(upvoteCount)}
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
        <div className='flex inline-block items-center justify-center text-right md:items-end md:justify-end'>
          <div className='inline-block'>
            <HeaderButtons
              handle={handle}
              display_name={display_name}
              user_id={user_id}
              isFollowing={isFollowing}
              onFollow={onFollow}
              isBlockedByProfile={isBlockedByProfile}
              isBlockingProfile={isBlockingProfile}
              onBlock={onBlock}
              onEdit={onEdit}
              clips={clips}
              hookCreatorLabel={hookCreatorLabel}
            />
          </div>
        </div>
      </div>
    </section>
  );
};

const ProfileHeader = observer(
  ({
    profile,
    isFlagged,
    followerCount,
    followingCount,
    playCount,
    upvoteCount,
    onFollow,
    isFollowing,
    isBlockedByProfile,
    isBlockingProfile,
    onBlock,
    clips,
    remixesInspiredCount,
    onEdit,
    onOpenFollowers,
    onOpenFollowing,
    onOpenRemixesInspired,
    hookCreatorLabel,
  }: ProfileHeaderProps) => {
    return (
      <>
        <div className='z-20 flex flex-col gap-8 py-0'>
          <div className='flex w-full flex-col'>
            <div className='z-1 flex h-full flex-col items-center justify-end md:items-start'>
              <ImageWithFallback
                imageSize={LARGE_IMAGE}
                className={
                  'z-20 h-[120px] w-[120px] rounded-full border-[6px] border-solid border-[rgba(255,255,255,0.10)]'
                }
                src={profile.avatar_image_url}
                alt={`Profile picture for ${
                  profile.display_name || profile.handle
                }`}
              />

              <div className='mt-4 flex w-full flex-col gap-2'>
                <ProfileMetadata
                  playCount={playCount}
                  upvoteCount={upvoteCount}
                  display_name={profile.display_name}
                  handle={profile.handle}
                  user_id={profile.user_id}
                  profile_description={profile.profile_description}
                  spotify_link={profile.spotify_link}
                  soundcloud_link={profile.soundcloud_link}
                  x_link={profile.x_link}
                  instagram_link={profile.instagram_link}
                  youtube_link={profile.youtube_link}
                  isFlagged={isFlagged}
                  followerCount={followerCount}
                  followingCount={followingCount}
                  isFollowing={isFollowing}
                  onFollow={onFollow}
                  isBlockedByProfile={isBlockedByProfile}
                  isBlockingProfile={isBlockingProfile}
                  onBlock={onBlock}
                  clips={clips}
                  remixesInspiredCount={remixesInspiredCount}
                  className='flex flex-col'
                  onEdit={onEdit}
                  onOpenFollowers={onOpenFollowers}
                  onOpenFollowing={onOpenFollowing}
                  onOpenRemixesInspired={onOpenRemixesInspired}
                  userTags={profile.user_inputted_genres}
                  hookCreatorLabel={hookCreatorLabel}
                />
              </div>
            </div>
          </div>
        </div>
      </>
    );
  }
);

export default ProfileHeader;
